#include "TextureManager.h"

using namespace DirectX;

TextureManager::TextureManager(void) : FOLDER("Textures/")
{

}


TextureManager::~TextureManager(void)
{
}

bool TextureManager::LoadTexture(std::string filename)
{
  CurrentContext ctx = CurrentContext::GetInstance();
  if(m_texturesMap[filename] == 0)
  {
    TextureDesc* desc = new TextureDesc();
    if(FAILED(D3DX11CreateShaderResourceViewFromFile(ctx.Device, (FOLDER + filename).c_str() ,0,0,&desc->ColorMap,0)))
    {
      delete desc;
      return false;
    }

    D3D11_SAMPLER_DESC colorMapDesc;
    ZeroMemory(&colorMapDesc, sizeof(colorMapDesc));

    colorMapDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    colorMapDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    colorMapDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    colorMapDesc.MipLODBias = 0;
    colorMapDesc.MinLOD = 0;
    colorMapDesc.MaxLOD = D3D11_FLOAT32_MAX;
    

    if(FAILED(ctx.Device->CreateSamplerState(&colorMapDesc, &desc->ColorMapSampler)))
    {
      delete desc;
      DXTRACE_MSG("Failed to create color map sampler state!");
      return false;
    }

    m_texturesMap[filename] = desc;
  }
  
  return true;
}

TextureDesc* TextureManager::GetTexture(std::string filename)
{
  if(m_texturesMap[filename] == 0)
  {
    if(this->LoadTexture(filename) == false)
      return 0;
  }

  return m_texturesMap[filename];
}
